/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package NetworkRequests;

import Enum.*;
import Forms.QueryResultForm;
import Main.Program;
import java.io.*;
import javax.microedition.io.*;

/**
 *
 * @author Hmong
 */
public class WhoisHttpRequest extends WhoisRequest {

    private String _Url;
    private String _Params;
    private int _HttpMethod;

    public WhoisHttpRequest(String domain, String url, String params, int httpMethod){
        super(domain);

        _Url = url;
        _Params = params;
        _HttpMethod = httpMethod;
    }

    public void run() {
        String queryResult = null;

        try {
            String netAddress = _Url + _Params;
            HttpConnection http;//创建一个http的连接
            http = (HttpConnection) Connector.open(netAddress);

            if (HttpMethod.Get == _HttpMethod)
                http.setRequestMethod(HttpConnection.GET); //设置连接方式
            else if(HttpMethod.Post == _HttpMethod)
                http.setRequestMethod(HttpConnection.POST); //设置连接方式
            else
                throw new Exception("Invalid Http Method");

            DataInputStream dis = http.openDataInputStream();//打开连接的输入流

            byte[] btData = new byte[1024 * 10];
            int nActualRead = dis.read(btData);
            if (0 < nActualRead)
                queryResult = new String(btData, 0, nActualRead, "UTF-8");
            else
                queryResult = "[Error] Query Fail";

            dis.close();
            http.close();
        } catch (IOException ex) {
            ex.printStackTrace();

            queryResult = "[Error] " + ex.getMessage();
        } catch(Exception ex){
            queryResult = "[Error] " + ex.getMessage();
        }

       QueryResultForm form = new QueryResultForm(queryResult);
       Program.GetDisplay().setCurrent(form);
    }

}
